package org.springblade.modules.admin.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.springblade.common.cache.DictCache;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.ProjectDTO;
import org.springblade.modules.admin.dto.parts.SparepartPricesSearchDTO;
import org.springblade.modules.admin.entity.Building;
import org.springblade.modules.admin.entity.BuildingElevatorTemplate;
import org.springblade.modules.admin.entity.BuildingExt;
import org.springblade.modules.admin.service.BuildingElevatorTemplateService;
import org.springblade.modules.admin.service.BuildingService;
import org.springblade.modules.admin.vo.BuildingElevatorTemplateVO;
import org.springblade.modules.admin.vo.BuildingExtVO;
import org.springblade.modules.admin.vo.ProjectVO;
import org.springblade.modules.admin.vo.SparepartPricesVO;
import org.springblade.modules.system.entity.Dict;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static org.springblade.modules.admin.service.BuildingService.PROJECT_TYPE_CODE;

/**
 * @Description 项目管理
 * @Author ysq
 * @Date 2021/8/24
 **/
@RestController
@AllArgsConstructor
@RequestMapping("/admin/project")
@Api(value = "项目管理", tags = "项目管理接口")
public class ProjectController extends BladeController {

	private final BuildingService buildingService;
	private final BuildingElevatorTemplateService betService;

	/**
	 * 分页
	 */
	@GetMapping("/list")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "项目列表分页")
	public R<IPage<ProjectVO>> list(Building building, Query query) {
		IPage<ProjectVO> pages = buildingService.selectProjectPage(Condition.getPage(query), building);
		return R.data(pages);
	}

	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "项目扩展信息详情")
	@GetMapping("/detail")
	public R<BuildingExt> detail(Long buildingId) {
		return R.data(buildingService.selectBuildingExtDetail(buildingId));
	}

	/**
	 * 新增/编辑
	 */
	@PostMapping()
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "项目新增/编辑")
	public R<Long> saveOrEdit(@RequestBody @Valid ProjectDTO project) {
		List<BuildingElevatorTemplate> templates = project.getTemplates();
		templates.forEach(o -> o.setStatus(1));
		project.setTemplates(templates);
		return R.data(buildingService.projectSaveOrEdit(project));
	}


	@PostMapping("save/batch")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "项目新增/编辑")
	public R<Boolean> saveBatch(@RequestBody @Valid List<ProjectDTO> projects) {
		projects.forEach(project -> {
			List<BuildingElevatorTemplate> templates = project.getTemplates();
			templates.forEach(o -> o.setStatus(2));
			project.setTemplates(templates);
			buildingService.projectSaveOrEdit(project);
		});
		return R.status(true);
	}

	@GetMapping("/getProjectType")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "获取项目类型集合")
	public R getProjectType() {
		List<Dict> list = DictCache.getList(PROJECT_TYPE_CODE);
		return R.data(list);
	}

	@GetMapping("/getALlCityNameList")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "获取区域下拉框数据")
	public R getALlCityNameList() {
		List<String> list = buildingService.getALlCityNameList();
		return R.data(list);
	}

	@GetMapping("/getALlAdNameList")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "根据市获取镇区下拉框数据")
	public R getALlAdNameList(@ApiParam(value = "市区名称", required = true) @RequestParam String cityName) {
		List<String> list = buildingService.getALlAdNameList(cityName);
		return R.data(list);
	}

	@GetMapping("/building/elevator/template/list")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "根据项目获取所有项目电梯关联模板")
	public R getBuildingElevatorTemplateList(Long buildingId) {
		List<BuildingElevatorTemplate> buildingElevatorTemplates = betService.list(Wrappers.<BuildingElevatorTemplate>lambdaQuery().eq(BuildingElevatorTemplate::getBuildingId, buildingId));
		if (ObjectUtil.isNotEmpty(buildingElevatorTemplates)) {
			buildingElevatorTemplates.forEach(e -> {
				List<String> names = Func.toStrList("/", e.getName());
				e.setTemplates(names.stream().map(k -> {
					BuildingElevatorTemplateVO templateVO = new BuildingElevatorTemplateVO();
					templateVO.setName(k);
					return templateVO;
				}).collect(Collectors.toList()));
			});
		}
		return R.data(buildingElevatorTemplates);
	}


	/**
	 * 下载任务调用excel
	 *
	 * @param response
	 * @param building
	 * @throws IOException
	 */
	@PostMapping("/down/excel")
	@ApiOperation("下载项目列表")
	public void downDispatchExcel(HttpServletResponse response, @RequestBody Building building) throws IOException {
		Query query = new Query();
		query.setSize(0);
		IPage<ProjectVO> page = Condition.getPage(query);
		final List<ProjectVO> records = buildingService.selectProjectPage(page, building).getRecords();
		ExcelWriter excelWriter = null;
		ServletOutputStream outputStream = response.getOutputStream();
		try {
			List<List<String>> rows = new ArrayList<>();
			List<String> title = CollUtil.newArrayList("类型", "名称", "项目别名", "地址", "梯数", "联系人", "手机号", "创建时间", "最后更新时间");
			rows.add(title);
			for (ProjectVO projectVO : records) {
				List<String> row = new ArrayList<>();
				row.add(projectVO.getTypeName());
				row.add(projectVO.getName());
				row.add(projectVO.getAliasString());
				row.add(projectVO.getAddress());
				row.add(projectVO.getEleTotal().toString());
				row.add(projectVO.getContactsName());
				row.add(projectVO.getPhone());
				row.add(DateUtil.format(projectVO.getCreateTime(), "yyyy-MM-dd HH:mm:ss"));
				row.add(DateUtil.format(projectVO.getUpdateTime(), "yyyy-MM-dd HH:mm:ss"));
				rows.add(row);
			}
			String fileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".xlsx";
			setResponseHeader(response, fileName);
			excelWriter = ExcelUtil.getBigWriter(rows.size());
			excelWriter.write(rows, true);
			excelWriter.flush(outputStream, true);
		} catch (
			Exception e) {
			e.printStackTrace();
		} finally {
			if (excelWriter != null) {
				excelWriter.close();
			}
			outputStream.close();
		}
	}

	/**
	 * 功能描述: 发送响应流方法
	 */
	private void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(), "ISO8859-1");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
